package cn.cjlmonster.demo02.utils;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.LocaleList;
import android.util.DisplayMetrics;

import java.util.Locale;

import cn.cjlmonster.demo02.Configs;

/**
 * Created by CJL on 2021/9/1 19:26.
 */
public class LanguageUtils {

    public static void changeLanguage(Context context, boolean isSetLocale) {
        saveDefaultLocale();
        if (isSetLocale) getAttachBaseContext(context);
    }

    private static void saveDefaultLocale() {
        Locale defaultLocale;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            defaultLocale = LocaleList.getDefault().get(0);
        } else {
            defaultLocale = Locale.getDefault();
        }
        SPUtils.getInstance().putString(Configs.DEFAULT_LOCALE, defaultLocale.toString());
    }

    public static Context getAttachBaseContext(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return updateResourcesUpN(context);
        } else {
            return updateResourcesDownN(context);
        }
    }

    public static Locale getLocale() {
        String lan = SPUtils.getInstance().getString(Configs.CURRENT_LANGUAGE, "sys");
        Locale mLocale;
        switch (lan) {
            case "zh_CN":
                mLocale = Locale.SIMPLIFIED_CHINESE;
                break;
            case "zh_TW":
            case "zh_HK":
                mLocale = Locale.TRADITIONAL_CHINESE;
                break;
            case "en":
                mLocale = Locale.ENGLISH;
                break;
            default:
                String default_locale = SPUtils.getInstance().getString(Configs.DEFAULT_LOCALE, "en");
                if (default_locale.equals("zh_HK")) default_locale = "zh_TW";
                String[] lo = default_locale.split("_");
                mLocale = new Locale(lo[0], lo[1]);
                break;
        }
        return mLocale;
    }

    @TargetApi(Build.VERSION_CODES.N)
    private static Context updateResourcesUpN(Context context) {
        Resources resources = context.getResources();
        Locale mLocale = getLocale();
        LocaleList.setDefault(new LocaleList(mLocale));
        Configuration conf = resources.getConfiguration();
        conf.setLocale(mLocale);
        return new ContextWrapper(context.createConfigurationContext(conf));
    }

    private static Context updateResourcesDownN(Context context) {
        Resources resources = context.getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        Locale mLocale = getLocale();
        Locale.setDefault(mLocale);
        Configuration conf = resources.getConfiguration();
        conf.setLocale(mLocale);
        resources.updateConfiguration(conf, dm);
        return new ContextWrapper(context);
    }
}
